package org.rslai.tcedit.dao.hibernate;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.springframework.dao.DataRetrievalFailureException;

/**
 * 子类继承这个父类后则实现简单的CRUD方法
 * 
 * @author rslai
 * @param <T>
 */
public abstract class GenericDynamicTableHibernateDao<T> extends GenericHibernateDao<T> {
	private final Class<T> clazz;

	private Map<String, String> entityNameMap = new HashMap<String, String>();

	public GenericDynamicTableHibernateDao(Class<T> clazz) {
		super(clazz);
		this.clazz = clazz;
	}

	@Override
	public T query(Serializable id) {
		throw new IllegalArgumentException("请调用带productID参数的query方法: " + clazz.getName());
	}

	@SuppressWarnings("unchecked")
	public T query(String productID, Serializable id) {
		T t = (T) hibernateTemplate.get(getEntityName(productID), id);
		if (t == null)
			throw new DataRetrievalFailureException("Object not found.");
		// it is strange that load() method return a lazy-loading proxy object
		// and it may cause LazyInitializationException!
		return t;
	}

	@Override
	public void create(T t) {
		throw new IllegalArgumentException("请调用带productID参数的create方法: " + clazz.getName());
	}

	public void create(String productID, T t) {
		hibernateTemplate.save(getEntityName(productID), t);
	}

	/**
	 * 返回实体名称
	 * @param dynamicTableName 动态表名（此处是产品ID）
	 * @return
	 */
	protected String getEntityName(String dynamicTableName) {
		String entityName = (String) entityNameMap.get(dynamicTableName);
		if (entityName == null) {
			entityName = clazz.getName() + "_" + dynamicTableName;
			entityNameMap.put(dynamicTableName, entityName);
		}
		return entityName;
	}

}
